package com.huluobo.base.net

import com.blankj.utilcode.util.SPUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *  Created by LC on 2024/7/19.
 *   companion object 伴生对象,其中的内容都是单例的
 *   把RetrofitManager 改成Object开头,也可以实现当前类为单例模式
 */
class RetrofitManager {
    companion object {
        fun getRetrofit(): Retrofit {
            //Okhttp
            val okHttpClientBuilder = OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
//                .addInterceptor(object : Interceptor {
//                    override fun intercept(chain: Interceptor.Chain): Response {
//                        val token = SPUtils.getInstance().getString(Const.PARAM_TOKEN)
//                        val newBuilder = chain.request().newBuilder()
//                        newBuilder.addHeader(Const.PARAM_TOKEN, token)
//                        return chain.proceed(newBuilder.build())
//                    }
//                })
                .addInterceptor {
                    val token = SPUtils.getInstance().getString(Const.PARAM_TOKEN)
                    val newBuilder = it.request().newBuilder()
                    newBuilder.addHeader(Const.PARAM_TOKEN, token)
                    it.proceed(newBuilder.build())
                }

            //Retrofit
            val retrofit = Retrofit.Builder()
                .baseUrl(Const.baseUrl)
                .client(okHttpClientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

            return retrofit.build()
        }
    }
}